package serializer

import (
	"context"
	"go-mall/dao"
	"go-mall/model"
	"strconv"
)

type Order struct {
	Id      uint    `json:"id"`
	OrderId string  `json:"order_id"`
	Num     int     `json:"num"`
	Type    uint    `json:"type"`
	Money   float64 `json:"money"`
	UserId  uint    `json:"user_id"`
}
type Orders struct {
	OrderId string      `json:"order_id"`
	Num     int         `json:"num"`
	Type    uint        `json:"type"`
	Money   float64     `json:"money"`
	List    interface{} `json:"list"`
}

type retProduct struct {
	Id      uint   `json:"id"`
	Name    string `json:"name"`
	Price   string `json:"price"`
	ImgPath string `json:"img"`
	Num     int    `json:"num"`
}

type retAddress struct {
	Id      uint   `json:"id"`
	Name    string `json:"name"`
	Phone   string `json:"phone"`
	Address string `json:"address"`
}

func BuildOrder(order *model.Order) Order {
	return Order{
		Id:      order.ID,
		OrderId: order.OrderId,
		Num:     order.Num,
		Type:    order.Type,
		Money:   order.Money,
		UserId:  order.UserId,
	}
}

func BuildOrders(ctx context.Context, items []*model.Order) []*Orders {
	productDao := dao.NewProductDao(ctx)
	addressDao := dao.NewAddressDao(ctx)
	orderDao := dao.NewOrderDao(ctx)

	var result []*Orders
	//单笔订单下的所有的item
	for _, item := range items {

		//查询item
		orders, _ := orderDao.GetOrderItemById(item.OrderId)
		var retOrder Orders
		//	拼接数据
		retOrder.OrderId = item.OrderId
		retOrder.Num = item.Num
		retOrder.Money = item.Money
		retOrder.Type = item.Type

		type list struct {
			Product retProduct `json:"product"`
			Address retAddress `json:"address"`
		}
		var retList []list
		for _, order := range orders {
			//地址
			address, _ := addressDao.GetAddressByAid(strconv.Itoa(int(order.AddressId)))
			//商品
			product, _ := productDao.GetProductById(order.ProductId)
			retA := retAddress{
				Id:      address.ID,
				Name:    address.Name,
				Phone:   address.Phone,
				Address: address.Address,
			}
			retP := retProduct{
				Id:      product.ID,
				Name:    product.Name,
				Price:   product.DiscountPrice,
				ImgPath: product.ImgPath,
				Num:     order.Num,
			}
			ordersList := list{
				Product: retP,
				Address: retA,
			}
			retList = append(retList, ordersList)
		}
		retOrder.List = retList
		result = append(result, &retOrder)
	}
	return result
}
